<?php

namespace app\admin\controller;

use app\common\model\Category as CategoryModel;
use think\Controller;
use think\Request;

class Category extends Common
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $list = CategoryModel::all();
        return responseData('success', '获取列表成功', $list);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $formData = $request->param();
        $result = $this->validate(
            $formData,
            'app\admin\validate\Category');

        if (true !== $result) {
            // 验证失败 输出错误信息
            return responseData('fail', '缺少参数', $result)->code(400);
        } else {
            $model = new CategoryModel;
            $model->data([
                'title' => $formData['title'],
                'model_id' => $formData['model_id'],
                'parent_id' => $formData['parent_id'],
                'path' => $formData['path'],
            ]);
            $id = $model->save();
            if ($id) {
                $this->setCategoryCache();
                return responseData('success', '添加成功', $id);
            } else {
                return responseData('fail', '添加失败！', $id);
            }
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $formData = $request->param();
        $result = $this->validate(
            $formData,
            'app\admin\validate\Category');

        if (true !== $result) {
            // 验证失败 输出错误信息
            return responseData('fail', '缺少参数', $result)->code(400);
        } else {
            $model = new CategoryModel;
            $id = $model->save([
                'title' => $formData['title'],
                'model_id' => $formData['model_id'],
                'parent_id' => $formData['parent_id'],
                'path' => $formData['path'],
            ], ['id' => $id]);
            if ($id) {
                $this->setCategoryCache();
                return responseData('success', '更新成功', $id);
            } else {
                return responseData('fail', '更新失败！', $id);
            }
        }

    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $result = CategoryModel::where('id='.$id)->delete();
        if($result) {
            $this->setCategoryCache();
            return responseData('success', '删除成功', $result);
        }
    }
}
